package pers.twf.twfRpc.bootstrap;

import pers.twf.twfRpc.RpcApplication;
import pers.twf.twfRpc.config.RegistryConfig;
import pers.twf.twfRpc.config.RpcConfig;
import pers.twf.twfRpc.model.ServiceMetaInfo;
import pers.twf.twfRpc.registry.LocalRegistry;
import pers.twf.twfRpc.registry.Registry;
import pers.twf.twfRpc.registry.RegistryFactory;
import pers.twf.twfRpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 提供者启动类
 */
public class ProviderBootstrap {
    /**
     * 提供者注册初始化
     * @param serviceRegisterInfos
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfos) {
        RpcApplication.init();
        //        注册服务到注册中心
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfos) {
            String serviceName = serviceRegisterInfo.getServiceName();
//            本地服务注册
            LocalRegistry.register(serviceName,serviceRegisterInfo.getImplClass());
//            注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServiceHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServicePort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName+"服务注册失败",e);
            }
        }
//        启动TCP服务
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(RpcApplication.getRpcConfig().getServicePort());
    }
}
